import { useMount } from 'ahooks';
import { Spin } from 'antd';
import { cloneDeep } from 'lodash';
import React, { Suspense, useState } from 'react';
import { useContextSelector } from 'use-context-selector';

import commonService from '@/api/services/commonService';
import { KnowledgeSubPageType } from '@/pages/knowledge-manage';
import { useSystemStore } from '@/store/useSystemStore';
import { appSystemModuleTemplates } from '@/types/workflow/template/constants';

import { AppContext, TabEnum } from '../../context';

import Flow from './components/Flow';
import Header from './components/Header';
import WorkflowContextProvider, { WorkflowContext } from './context';

// 局部loading组件，避免使用顶层的CircleLoading
function LocalLoading() {
  return (
    <div className="flex h-full w-full items-center justify-center">
      <Spin size="default" />
    </div>
  );
}

// 定义权限管理子页面类型
type PermissionSubPageType = 'permission' | 'user' | 'role' | 'share' | 'qaPermission';
// 定义知识管理子页面类型

const Report = React.lazy(() => import('@/pages/report'));
const PermissionManage = React.lazy(() => import('@/pages/permission-manage'));
const KnowledgeManage = React.lazy(() => import('@/pages/knowledge-manage'));
const AppTest = React.lazy(() => import('@/pages/application-test'));
const SharePage = React.lazy(() => import('@/pages/share'));

function WorkflowEdit() {
  const { appDetail, currentTab, preview } = useContextSelector(AppContext, (e) => e);
  const [permissionSubPage, setPermissionSubPage] = useState<PermissionSubPageType>('qaPermission');
  const [knowledgeSubPage, setKnowledgeSubPage] = useState<KnowledgeSubPageType>('datasets');
  const initData = useContextSelector(WorkflowContext, (v) => v.initData);

  const handlePermissionSubPageChange = (page: PermissionSubPageType) => {
    setPermissionSubPage(page);
  };

  const handleKnowledgeSubPageChange = (page: KnowledgeSubPageType) => {
    setKnowledgeSubPage(page);
  };

  const initSystemData = async () => {
    const res = await commonService.getSystemInitData();
    useSystemStore.getState().initStaticData(res);
  };

  useMount(() => {
    initSystemData();
    initData(
      cloneDeep({
        nodes: appDetail.modules || [],
        edges: appDetail.edges || [],
      }),
      true,
    );
  });

  return (
    <div className="flex h-full w-full flex-col">
      <Header />
      {currentTab === TabEnum.appEdit || preview ? (
        <Suspense fallback={<LocalLoading />}>
          <Flow preview={preview} />
        </Suspense>
      ) : (
        <div className="m-2 flex h-full flex-col overflow-hidden rounded-[12px]">
          <Suspense fallback={<LocalLoading />}>
            {currentTab === TabEnum.knowledge && (
              <KnowledgeManage
                subPage={knowledgeSubPage}
                onPageChange={handleKnowledgeSubPageChange}
                appType="workflow"
              />
            )}
            {currentTab === TabEnum.permission && (
              <PermissionManage
                subPage={permissionSubPage}
                onPageChange={handlePermissionSubPageChange}
              />
            )}
            {currentTab === TabEnum.reporte && <Report renderTitle={undefined} />}
            {currentTab === TabEnum.test && <AppTest />}
            {currentTab === TabEnum.share && <SharePage />}
          </Suspense>
        </div>
      )}
      {/* <Flow /> */}
    </div>
  );
}

// const systemModuleTemplates: FlowNodeTemplateType[] = [
//   // 系统模块模板列表，后续可配置
// ];

function Render() {
  return (
    <WorkflowContextProvider basicNodeTemplates={appSystemModuleTemplates}>
      <WorkflowEdit />
    </WorkflowContextProvider>
  );
}

export default Render;
